import { View, Image } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useState, useEffect, useMemo, useLayoutEffect } from "react";
import { LgTabs, LgTab } from "@/pages/components/tabs";
import Header from "@/pages/messageApp/component/header";
import Todo from "../todoList";
import ClassNotice from "../classNotice";
import SchoolNotice from "../schoolNotice";
import SystemMes from "../systemMes";
import Chat from "../online";
import { getStorage } from "@/pages/components/utils";
import { useDispatch, useSelector } from "react-redux";
import Utils from "@/utils/index";
import Proxy from "@/network/proxy";
import { HttpGet } from "../../../network/servers";
import Toast from "../component/toast";
import md5 from "md5";
import { useGetClientType, useGetIpAndPort } from "@/utils/myUtils";
import useRedirectNotice from "../../../hooks/useRedirectNotice";
import "./index.scss";

const storage = getStorage();
let ClientType = useGetClientType();

let timer: any = null;
let reconnectCount: any = 0;

export default function App(props) {
  const { userInfo, isEdu, noticeAddr, lg_ic, mainServer } = useSelector(
    (state: any) => state.commonData
  );

  //自动跳转到发布通知页面
  useRedirectNotice(noticeAddr, lg_ic, userInfo.SchoolID);
  const dispatch = useDispatch();
  const [updateList, setUpdateList] = useState<any>([]);

  const [currentTab, setCurrentTab] = useState("");
  const [remindSocket, setRemindSocket] = useState<any>();
  const [chatMsgCount, setChatMsgCount] = useState(0);

  const [wsClient, setWsClient] = useState<any>();

  const getToken = () => {
    if (Utils.getQueryVariable("env") === "weapp") {
      return Utils.getQueryVariable("lg_tk");
    } else {
      return storage.get("token") || Utils.getQueryVariable("lg_tk");
    }
  };
  const bodyDom = useMemo(() => {
    if (currentTab === "待办事项") {
      return <Todo />;
    } else if (currentTab === "班级通知") {
      return <ClassNotice />;
    } else if (currentTab === "部门通知") {
      return <SchoolNotice />;
    } else if (currentTab === "交流消息") {
      return <Chat />;
    } else if (currentTab === "系统提醒") {
      return <SystemMes />;
    }
  }, [currentTab]);

  const forbidModule = useMemo(() => {
    if (isEdu) {
      return ["部门通知"];
    }
    return [];
  }, [isEdu]);

  const choTab = (value, key) => {
    setCurrentTab(key);
    getNewRemindCount();
  };

  const choOptionItem = () => {
    Taro.navigateTo({
      url: "pages/messageApp/systemSet/index",
    });
  };

  function sumUnReadCount(objArray) {
    if (objArray.length === 0) {
      return 0;
    }

    return objArray.reduce((total, obj) => {
      if (obj.unReadCount !== undefined) {
        return total + obj.unReadCount;
      }
      return total;
    }, 0);
  }

  const createPushWebSocket = () => {
    // if (Utils.getSystemInfo() === 'weapp') {  //暂时没有映射在线交流
    //     setUpdateList(kindList2)
    //     return
    // }
    HttpGet({
      url: `/api/commons/system/getServerInfo?sysIds=460`,
      data: {},
    }).then((result) => {
      let url = result?.data[0]?.webSvrAddr || "";
      if (url) {
        //当460的地址存在，才会进行后续操作
        if (Utils.getSystemInfo() === "weapp" && url.includes("http://")) {
          url = mainServer + "lg_im/";
        }

        dispatch({
          type: "SET_CHATURL",
          data: url,
        });
        HttpGet({
          url: url + "/api/commons/school/system/info",
          data: {
            token: Utils.getNowToken(),
            schoolId: userInfo.SchoolID,
          },
          showError: false,
        }).then((res) => {
          let socketUrl = "";
          window.chatSocket && window.chatSocket.close();
          if (Utils.getSystemInfo() === "weapp") {
            //124环境才有在线交流外网
            let chatWS = res.data?.chatWs || "";

            if (chatWS.includes("ws://")) {
              chatWS = "ws://" + useGetIpAndPort(url) + "/im_chat/";
              socketUrl = Proxy.transmitUrlToVisit(
                chatWS,
                "wss://campus.lancooedu.com:50000"
              );
            } else {
              socketUrl = chatWS;
            }
          } else {
            socketUrl = res.data.chatWs;
          }
          let socket = new WebSocket(socketUrl);

          setWsClient(socket);
          window.chatSocket = socket;
          socket.onopen = function (e) {
            let all = {
              msgType: "3",
              clientType: ClientType,
              token: getToken(),
              data: {
                userId: userInfo.UserID,
              },
            };
            socket.send(JSON.stringify(all));
          };
          socket.onmessage = function (e) {
            var result = JSON.parse(e.data);
            switch (result.msgType) {
              case 1:
                socket.send(
                  JSON.stringify({
                    msgType: 100,
                    clientType: ClientType,
                    token: getToken(),
                    data: {
                      clientType: ClientType,
                      msgId: result.data.msgId,
                      receiverId: result.data.senderId,
                      receiverName: result.data.senderId || "",
                      schoolId: userInfo.SchoolID,
                      sessionType: result.msgType,
                      receiverAvatarPath: result?.data?.senderAvatarPath || "",
                    },
                  })
                );
                socket.send(
                  JSON.stringify({
                    msgType: 4,
                    clientType: ClientType,
                    token: getToken(),
                    data: {},
                  })
                );
                break;
              case 2:
                socket.send(
                  JSON.stringify({
                    msgType: 100,
                    clientType: ClientType,
                    token: getToken(),
                    data: {
                      clientType: ClientType,
                      msgId: result.data.msgId,
                      groupId: result.data?.groupId,
                      groupName: result.data?.groupName,
                      receiverId: result.data.senderId,
                      receiverName: result.data.senderId || "",
                      schoolId: userInfo.SchoolID,
                      sessionType: result.msgType,
                      receiverAvatarPath: result?.data?.avatarPath || "",
                    },
                  })
                );
                socket.send(
                  JSON.stringify({
                    msgType: 4,
                    clientType: ClientType,
                    token: getToken(),
                    data: {},
                  })
                );
                break;
              case 3:
                socket.send(
                  JSON.stringify({
                    msgType: 10,
                    clientType: ClientType,
                    token: getToken(),
                    data: {},
                  })
                );
                break;
              case 4:
                let chatList = result.data || [];
                chatList.sort(function (a, b) {
                  if (a.seat === 1 && b.seat === 0) {
                    return -1; // a在b前面
                  } else if (a.seat === 0 && b.seat === 1) {
                    return 1; // a在b后面
                  } else if (a.seat === 1 && b.seat === 1) {
                    return b.levelNum - a.levelNum; // levelNum越大，越靠前
                  } else {
                    return 0; // 保持原有顺序
                  }
                });

                let chatUnreadCount = sumUnReadCount(chatList);
                setChatMsgCount(chatUnreadCount);
                dispatch({
                  type: "SESSIONLIST",
                  data: chatList,
                });
                break;
              case 7:
                Taro.showToast({
                  title: "移除会话成功",
                });
                socket.send(
                  JSON.stringify({
                    msgType: 4,
                    clientType: ClientType,
                    token: getToken(),
                    data: {},
                  })
                );
                break;
              case 10: //拉取离线消息
                socket.send(
                  JSON.stringify({
                    msgType: 4,
                    clientType: ClientType,
                    token: getToken(),
                    data: {},
                  })
                );
                break;
              case 11: //屏蔽成功
              case 12:
                Taro.showToast({
                  title: "操作成功",
                });
                socket.send(
                  JSON.stringify({
                    msgType: 4,
                    clientType: ClientType,
                    token: getToken(),
                    data: {},
                  })
                );
                break;
              case 13:
              case 100:
                socket.send(
                  JSON.stringify({
                    msgType: 4,
                    clientType: ClientType,
                    token: getToken(),
                    data: {},
                  })
                );
                break;
              default:
                break;
            }
          };
          socket.onerror = function (e) {
            reconnectCount++;
            if (reconnectCount > 5) {
              window.chatSocket = null;
              setWsClient(null);
              return;
            } else {
              createPushWebSocket();
            }
          };
          socket.onclose = function () {
            console.log("已掉线，准备重连");
            let maxErrorCont = 10;
            if (Utils.getSystemInfo() === "weapp") {
              maxErrorCont = 100;
            }
            if (reconnectCount > maxErrorCont) {
              return;
            }
            clearInterval(timer);
            timer = null;
            setTimeout(() => {
              createPushWebSocket();
            }, 3000);
          };
        });
      }
    });
  };

  const getReadInfo = () => {
    HttpGet({
      url: "/api/commons/system/getSystemModular",
      data: {
        userType: userInfo.UserType,
        schoolId: userInfo.SchoolID,
        beEdu: isEdu ? 1 : 0,
      },
    }).then((result) => {
      let moduleArr = result.data.split(",");
      let moduleInfo = [] as any;
      moduleArr.forEach((item, index) => {
        /** 屏蔽未开发的模块 */
        // if (!forbidModule.includes(item)) {
        moduleInfo.push({
          type: item,
          title: item,
          name: item,
          select: false,
          categoryId: "",
          count: 0,
        });
        // }
      });
      console.log(666666666666)
      console.log(moduleInfo)
      /*
      type=todo
      type=onlineChat
      type=systemMessage
      */
      let url = window.location.href
      console.log(url)
      if (url.includes("type=todo")) {
        console.log("type=todo")
        moduleInfo[0].select = true;
        setCurrentTab(moduleInfo[0].name);
        setUpdateList(moduleInfo);
      } else if (url.includes("type=onSiteAnnouncement")) {
        console.log("type=onSiteAnnouncement")
        moduleInfo[1].select = true;
        setCurrentTab(moduleInfo[1].name);
        setUpdateList(moduleInfo);
      } else if (url.includes("type=onlineChat")) {
        console.log("type=onlineChat")
        moduleInfo[2].select = true;
        setCurrentTab(moduleInfo[2].name);
        setUpdateList(moduleInfo);
      } else if (url.includes("type=systemMessage")) {
        console.log("type=systemMessage")
        moduleInfo[3].select = true;
        setCurrentTab(moduleInfo[3].name);
        setUpdateList(moduleInfo);
      } else {
        console.log("type=")
        moduleInfo[0].select = true;
        setCurrentTab(moduleInfo[0].name);
        setUpdateList(moduleInfo);
      }
      // moduleInfo[0].select = true;
      // setCurrentTab(moduleInfo[0].name);
      // setUpdateList(moduleInfo);
    });
  };

  const getReadInfo2 = (res) => {
    let list = JSON.parse(JSON.stringify(updateList));
    console.log(77777)
    console.log(list)
    console.log(res)
    list.forEach((item) => {
      if (Number(res.systemCount) && item.name == "系统提醒") {
        //系统消息
        item.noRead = true;
        item.count = Number(res.systemCount);
      }
      if (Number(res.todoCount) && item.name == "待办事项") {
        //班级通知
        item.noRead = true;
        item.count = Number(res.todoCount);
      }
      // if (Number(res.noticeClassCount) && item.name == "站内通知") {
      //   //班级通知
      //   item.noRead = true;
      //   item.count = Number(res.noticeClassCount);
      // }
      if (Number(res.noticeSchoolCount) && item.name == "部门通知") {
        //学校通知
        item.noRead = true;
        item.count = Number(res.noticeSchoolCount);
      }
    });
    setUpdateList(list);
  };

  const createRemindSocket = () => {
    let socketUrl = "",
      clientType = 1;
    Taro.getSysWeb({ sysId: "210" }, "web", function (data) {
      if (data.indexOf("ws://") > -1) {
        socketUrl = data;
      } else {
        if (data.indexOf("https") > -1) {
          socketUrl = "wss://" + data.split("https://")[1] + "/api/websocket/";
        } else {
          socketUrl = "ws://" + data.split("http://")[1] + "/api/websocket/";
          if (Utils.getSystemInfo() === "weapp") {
            clientType = 2;
            socketUrl = Proxy.transmitUrlToVisit(
              socketUrl,
              "wss://campus.lancooedu.com:50000"
            );
          }
        }
        // let url = data&&data.match(/^https?:\/\/.+:\d+/)[0]
        // if (url.includes('https') && Utils.getSystemInfo() === 'weapp') {  //小程序且使用wss
        //     socketUrl = 'wss://' + url.split('//')[1] + '/message-center/api/websocket/'
        // } else {  //非https协议使用代理
        //     socketUrl = 'ws://' + url.split('//')[1] + '/message-center/api/websocket/'
        //     if (Utils.getSystemInfo() === 'weapp') {
        //         clientType = 2
        //         socketUrl = Proxy.transmitUrlToVisit(socketUrl, 'wss://campus.lancooedu.com:50000')
        //     }
        // }
      }
      remindSocket && remindSocket.close();
      let socket = new WebSocket(socketUrl);
      setRemindSocket(socket);
      window.remindSocket = socket;
      socket.onopen = function () {
        socket.send(
          JSON.stringify({
            messageType: 1,
            clientType,
            userId: userInfo.UserID,
            encryptionCode: md5(userInfo.UserID).split("").reverse().join(""),
            param: {
              userId: userInfo.UserID,
              userType: userInfo.UserType,
              schoolId: userInfo.SchoolID,
            },
          })
        );
      };
      socket.onmessage = function (e) {
        let result = JSON.parse(e.data);
        switch (result.pushType || result.code) {
          case 1002:
            socket.send(
              JSON.stringify({
                messageType: 2,
                clientType,
                userId: userInfo.UserID,
                encryptionCode: md5(userInfo.UserID)
                  .split("")
                  .reverse()
                  .join(""),
                param: {
                  userId: userInfo.UserID,
                  userType: userInfo.UserType,
                  schoolId: userInfo.SchoolID,
                },
              })
            );
            break;
          case 1200:
            result.data && getReadInfo2(result.data);
            break;
          case 1000:
            Taro.showToast({
              title: "非法连接",
              icon: "none",
            });
            remindSocket.close();
            break;
          case 999:
            remindSocket.close();
            break;
          default:
            break;
        }
      };
    });
  };

  const getNewRemindCount = () => {
    let clientType = 1;
    if (Utils.getSystemInfo() === "weapp") {
      clientType = 2;
    }
    if (window.remindSocket && window.remindSocket?.readyState == 1) {
      window.remindSocket &&
        window.remindSocket.send(
          JSON.stringify({
            messageType: 2,
            clientType,
            userId: userInfo.UserID,
            encryptionCode: md5(userInfo.UserID).split("").reverse().join(""),
            param: {
              userId: userInfo.UserID,
              userType: userInfo.UserType,
              schoolId: userInfo.SchoolID,
            },
          })
        );
    }
    // if (window.chatSocket && window.chatSocket?.readyState == 1) {
    //     window.chatSocket && window.chatSocket.send(JSON.stringify({
    //         MessageType: 1001,
    //         ClientType,
    //         Data: {
    //             UserID: userInfo.UserID
    //         }
    //     }))
    // }
  };

  useEffect(() => {
    getReadInfo();
  }, []);

  useEffect(() => {
    if (updateList.length <= 0 || remindSocket) {
      return;
    }
    createRemindSocket();
  }, [updateList]);

  useEffect(() => {
    createPushWebSocket();
  }, []);

  useEffect(() => {
    return () => {
      clearInterval(timer);
      timer = null;
    };
  }, [wsClient]);

  useLayoutEffect(() => {
    window.getNewRemindCount = getNewRemindCount;
  }, []);

  return (
    <View className="message_app">
      <View className="message_top">
        <Header isLeft={false} isBlod={true} title="消息中心" />
        <View
          className={
            Utils.getSystemInfo() === "weapp"
              ? "tabs_container2"
              : "tabs_container"
          }
        >
          {updateList.length > 0 ? (
            <LgTabs
              onClick={choTab}
              customIcon={
                <View className="setting_icon">
                  <Image
                    onClick={choOptionItem}
                    style={{ width: "100%", height: "100%" }}
                    src={require("../images/setting.svg")}
                  ></Image>
                </View>
              }
              showIcon
              default={window.location.href.includes("type=todo") ? 0 :
              window.location.href.includes("type=onSiteAnnouncement") ? 1 :
              window.location.href.includes("type=onlineChat") ? 2 :
              window.location.href.includes("type=systemMessage") ? 3 
              : 0}
            >
              {updateList.map((item, index) => {
                return (
                  <LgTab
                    key={index}
                    count={
                      item.title === "交流消息" ? chatMsgCount : item.count
                    }
                    title={item.title}
                  />
                );
              })}
            </LgTabs>
          ) : (
            ""
          )}
        </View>
      </View>
      {bodyDom}
      <Toast />
    </View>
  );
}
